<template>
  <view class="edit-profile">
    <view class="form">
      <view class="form-item">
        <text class="label">头像</text>
        <button 
          class="avatar-wrapper"
          open-type="chooseAvatar"
          @chooseavatar="onChooseAvatar"
        >
          <image class="avatar" :src="form.avatar || defaultAvatarUrl" mode="aspectFill"></image>
        </button>
      </view>
      
      <view class="form-item">
        <text class="label">昵称</text>
        <input 
          type="nickname"
          v-model="form.nickName"
          placeholder="请输入昵称"
          class="input"
          @blur="onNicknameBlur"
        />
      </view>
      
      <view class="form-item">
        <text class="label">手机号</text>
        <input 
          type="number"
          v-model="form.mobile"
          placeholder="请输入手机号"
          class="input"
        />
      </view>
    </view>
    
    <button class="submit-btn" form-type="submit" @tap="handleSubmit">保存</button>
  </view>
</template>

<script>
import { updateUserInfo, updateUserRichInfo, getUserInfo } from '@/api/user'
import config from '@/config'

export default {
  data() {
    return {
      form: {
        avatar: '',
        nickName: '',
        mobile: ''
      },
      defaultAvatarUrl: 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0',
      shouldReturn: true
    }
  },
  
  onLoad(options) {
    this.loadUserInfo()
    if (options.stay === 'true') {
      this.shouldReturn = false
    }
  },
  
  methods: {
    async loadUserInfo() {
      try {
        const { data } = await getUserInfo()
        this.form = {
          avatar: data.avatar,
          nickName: data.nickName,
          mobile: data.mobile
        }
      } catch (error) {
        console.error('获取用户信息失败:', error)
      }
    },
    
    onChooseAvatar(e) {
      const { avatarUrl } = e.detail 
      this.form.avatarTempPath = avatarUrl
      this.form.avatar = avatarUrl
    },
    
    onNicknameBlur() {
      if (!this.form.nickName) {
        uni.showToast({
          title: '请输入昵称',
          icon: 'none'
        })
      }
    },
    
    async handleSubmit() {
      try {
        const { data: userInfo } = await getUserInfo()
        
        if (this.form.avatarTempPath && this.form.avatarTempPath.startsWith('wxfile://')) {
          const avatarUrl = await this.uploadAvatarFile(this.form.avatarTempPath)
          this.form.avatar = avatarUrl
        }
        
        const updateData = {
          nickName: this.form.nickName,
          mobile: this.form.mobile,
          avatar: this.form.avatar
        }
        
        if (this.form.avatar && (this.form.avatar.startsWith('http') || this.form.avatar.startsWith('/'))) {
          await updateUserRichInfo(userInfo.userId, updateData)
        } else if (this.form.avatar) {
          await updateUserInfo(userInfo.userId, updateData)
        } else {
          await updateUserInfo(userInfo.userId, {
            nickName: this.form.nickName,
            mobile: this.form.mobile
          })
        }
        
        uni.showToast({
          title: '保存成功',
          icon: 'success'
        })
        
        setTimeout(() => {
          if (!this.shouldReturn) {
            return
          }
          
          const pages = getCurrentPages()
          
          if (pages.length > 1) {
            const prevPage = pages[pages.length - 2]
            if (prevPage.route !== 'pages/login/login') {
              uni.navigateBack()
            } else {
              uni.switchTab({
                url: '/pages/index/index'
              })
            }
          } else {
            uni.switchTab({
              url: '/pages/index/index'
            })
          }
        }, 1500)
      } catch (error) {
        uni.showToast({
          title: error.message || '保存失败',
          icon: 'none'
        })
      }
    },
    
    async uploadAvatarFile(tempFilePath) {
      return new Promise((resolve, reject) => {
        uni.uploadFile({
          url: `${config.baseURL}/v1/upload/avatar`,
          filePath: tempFilePath,
          name: 'file',
          header: {
            'Authorization': `Bearer ${uni.getStorageSync('token')}`
          },
          success: (res) => {
            if (res.statusCode === 200) {
              const data = JSON.parse(res.data)
              resolve(data.data)
            } else {
              reject(new Error('上传头像失败'))
            }
          },
          fail: (err) => {
            console.error('上传头像错误:', err)
            reject(new Error('上传头像失败'))
          }
        })
      })
    }
  }
}
</script>

<style>
.edit-profile {
  padding: 30rpx;
}

.form-item {
  margin-bottom: 30rpx;
}

.label {
  display: block;
  font-size: 28rpx;
  color: #333;
  margin-bottom: 10rpx;
}

.input {
  height: 80rpx;
  padding: 0 20rpx;
  border: 1rpx solid #eee;
  border-radius: 8rpx;
  font-size: 28rpx;
}

.avatar-wrapper {
  text-align: center;
  padding: 0;
  width: 160rpx !important;
  height: 160rpx !important;
  border-radius: 50%;
  margin: 0 auto;
  background: none;
}

.avatar-wrapper::after {
  border: none;
}

.avatar {
  width: 100%;
  height: 100%;
  border-radius: 50%;
}

.submit-btn {
  margin-top: 60rpx;
  background: #3a8838;
  color: #fff;
  border-radius: 45rpx;
  height: 90rpx;
  line-height: 90rpx;
}
</style> 